<template>
  <div>
    <el-card class="mb-10">
      <CategorySelector :disabled="isEdit"></CategorySelector>
    </el-card>
    <el-card>
      <!-- 列表展示 -->
      <div v-if="!isEdit">
        <el-button class="mb-10" type="primary" :icon="Plus" @click="addAttr"
          :disabled="!categoryStore.category3Id">添加属性</el-button>

        <el-table :data="attrList" border>
          <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
          <el-table-column label="属性名" width="100" prop="attrName"></el-table-column>
          <el-table-column label="属性值列表">
            <template #default="{ row, $index }">
              <el-tag class="mr-5" type="success" v-for="attrVal in row.attrValueList" :key="attrVal.id">{{
                  attrVal.valueName
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template #default="{ row, $index }">
              <el-button type="warning" size="small" :icon="Edit" @click="editAttr(row)"></el-button>
              <el-popconfirm :title="`确认删除[${row.attrName}]么?`" @confirm="deleteAttr(row)">
                <template #reference>
                  <el-button type="danger" size="small" :icon="Delete"></el-button>
                </template>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 新增编辑展示 -->
      <div v-if="isEdit">
        <el-form :inline="true">
          <el-form-item label="属性名">
            <el-input type="text" v-model="attrForm.attrName" placeholder="输入属性名"></el-input>
          </el-form-item>
        </el-form>
        <div class="mb-10">
          <el-button type="primary" @click="addAttrVal" :disabled="!attrForm.attrName">添加属性值</el-button>
          <el-button @click="cancelSave">取消</el-button>
        </div>
        <el-table :data="attrForm.attrValueList" class="mb-10" border>
          <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
          <el-table-column label="属性名称">
            <template #default="{ row, $index }">
              <el-input v-if="row.inputVisible" ref="inputRef" v-model="row.valueName"
                @blur="inputBlur(row, $index)"></el-input>
              <div v-else @click="inputFocus(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row, $index }">
              <el-button type="danger" size="small" :icon="Delete" @click="deleteAttrVal($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-button type="primary" @click="onSave"
            :disabled="!(attrForm.attrValueList.length && attrForm.attrName)">保存</el-button>
          <el-button @click="cancelSave">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>

</template>

<script setup lang='ts'>
import useCategoryStore from '@/stores/category';
import { Delete, Edit, Plus, Watch } from '@element-plus/icons-vue';
import { nextTick, ref, watch } from 'vue';
import attrApi, { type AttrModel, type AttrValueModel } from '@/api/attr'
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash';

// 拿到三级分类的store
const categoryStore = useCategoryStore()

const isEdit = ref(false)  // 默认非编辑状态

// 用于存储属性数据
const attrList = ref<AttrModel[]>([])


const initAttrForm = (): AttrModel => ({
  attrName: '',
  attrValueList: [],
  categoryId: undefined,
  categoryLevel: 3
})
// 收集添加时的表单数据
const attrForm = ref<AttrModel>(initAttrForm())


const getList = async () => {
  try {
    const { category1Id, category2Id, category3Id } = categoryStore
    let result = await attrApi.attrInfoList(category1Id as number, category2Id as number, category3Id as number)
    attrList.value = result
  } catch (error) {
    ElMessage.error('获取平台属性列表失败，请重试')
  }
}

watch(() => categoryStore.category3Id, (nval) => {
  if (nval) {
    getList()
  } else {
    // 重置页面
    attrList.value = []
  }
}, { immediate: true })

// 添加属性的回调
const addAttr = () => {
  isEdit.value = true
}

// 添加属性值的回调
const addAttrVal = () => {
  attrForm.value.attrValueList.push({
    valueName: '',
    inputVisible: true   // 用来控制当前的属性值是否在input框中
  })

  nextTick(() => {
    inputRef.value?.focus() // 等待DOM更新，自动聚焦 
  })
}

// 保存的回调
const onSave = async () => {
  attrForm.value.categoryId = categoryStore.category3Id
  try {
    await attrApi.saveAttr(attrForm.value)
    ElMessage.success('保存成功')

    cancelSave()
    getList()
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

// 取消保存的回调
const cancelSave = () => {
  isEdit.value = false;  // 切换主界面显示

  attrForm.value = initAttrForm(); // 重置表单数据
}

// 编辑的回调
const editAttr = (row: AttrModel) => {
  isEdit.value = true
  attrForm.value = cloneDeep(row)
}

// 删除属性值的回调
const deleteAttrVal = (index: number) => {
  attrForm.value.attrValueList.splice(index, 1)
}

// 删除属性的回调
const deleteAttr = async (row: AttrModel) => {
  try {
    await attrApi.deleteAttr(row.id as number)
    ElMessage.success('删除属性成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败，请重试')
  }
}

const inputRef = ref<HTMLInputElement>()
// input聚焦事件
const inputFocus = (row: AttrValueModel) => {
  row.inputVisible = true  // 切换input的展示
  // 只能当input展示的时候才聚焦，否则获取不到组件实例
  // Vue中的恒心是一部的，当数据发生变化的时候，此时DOM还没更新
  // 需要等到DOM更新完毕后，才能获取到DOM元素
  // nextTick() 可以在状态改变后立即使用，以等待 DOM 更新完成

  nextTick(() => {
    inputRef.value?.focus()
  })
}

// input失焦事件
const inputBlur = (row: AttrValueModel, index: number) => {
  row.inputVisible = false

  // 帕努但输入的内容不能为空
  if (!row.valueName.trim()) {
    attrForm.value.attrValueList.splice(index, 1)  // 删除这条空数据
    ElMessage.error('输入的内容不能为空')
    return
  }

  // 判断输入的内容不能重复
  // attrForm.value.attrValueList  属性值列表
  // row 当前属性值
  // 在属性值列表中,一定有当前自己的这个属性值(row),判断的时候,需要把自己在数组中的位置排除掉之后,再进行判断有没有相同的
  const isRepeat = attrForm.value.attrValueList.some((item, idx) => {
    if (index == idx) {
      return false
    } else {
      return item.valueName == row.valueName
    }
  })

  if (isRepeat) {
    attrForm.value.attrValueList.splice(index, 1)
    ElMessage.error('输入的内容重复，请重新输入')
    return
  }


}
</script>

<style scoped>

</style>